package com.itheima.reggie.contronller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.LoginCode;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.UserDto;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.filter.LoginCheckFilter;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserContronller {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送验证码
     *
     * @param user
     * @param request
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpServletRequest request) {

        if (user == null || StringUtils.isBlank(user.getPhone())) {
            return R.error("验证码发送失败");
        }
        //生成验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        log.info("code:{}", code);
        //将验证码存到session域里面
        //request.getSession().setAttribute(user.getPhone(), code);

        //将验证码存到缓存里,时间设置为五分钟
        redisTemplate.opsForValue().set(LoginCode.USER_REDIS_KEY + user.getPhone(), code, 5L, TimeUnit.MINUTES);
        return R.success("验证码已发送");
    }

    /**
     * 登录校验
     *
     * @param userDto
     * @param request
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody UserDto userDto, HttpServletRequest request) {
        if (userDto == null || StringUtils.isEmpty(userDto.getPhone()) || StringUtils.isEmpty(userDto.getCode())) {
            return R.error("用户名或验证码不能为空");
        }
        //从session域里取验证码
        //String code = (String) request.getSession().getAttribute(userDto.getPhone());

        //从缓存里取验证码
        String code = (String) redisTemplate.opsForValue().get(LoginCode.USER_REDIS_KEY + userDto.getPhone());
        if (!userDto.getCode().equals(code)) {
            return R.error("验证码错误或失效了");
        }
        User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getPhone, userDto.getPhone()));
        if (user == null) {
            //说明没注册,给他注册一下
            user = new User();
            user.setPhone(userDto.getPhone());
            user.setStatus(1);
            userService.save(user);

        }
        if (user.getStatus() == 0) {
            return R.error("该账号已被禁用");
        }
        //清空session里面的验证码
        //request.getSession().removeAttribute(userDto.getPhone());

        //清空缓存里的验证码
        redisTemplate.delete(LoginCode.USER_REDIS_KEY + userDto.getPhone());
        //吧id存入session域里,用于登录验证
        //TODO id还存在session域里面,应该也存在缓存里
        request.getSession().setAttribute(LoginCode.USER_CHECKID, user.getId());
        return R.success(user);
    }

    @PostMapping("/loginout")
    public R<String> loginout(HttpServletRequest request) {
        //删除session域里面的id
        request.getSession().removeAttribute(LoginCode.USER_CHECKID);

        return R.success("退出成功");
    }


}
